import * as grpc from "@grpc/grpc-js";
import { PromiserHandlers } from "../typings";

export function fromPromiserHandlers<
  H extends grpc.UntypedServiceImplementation
>(ph: PromiserHandlers<H>): H {
  const handler = {} as any;

  Object.keys(ph).forEach((key) => {
    const promiserMethod = ph[key];
    const method: grpc.handleUnaryCall<unknown, unknown> = async (
      call,
      callBack
    ) => {
      const { request } = call;
      const output = await promiserMethod(request as any);
      callBack(null, output);
    };
    handler[key] = method;
  });
  return handler as H;
}
